require 'logger'
require 'flex_view/exceptions'
require 'flex_view/template_handler'
require 'flex_view/components'
require 'flex_view/view_file'
require 'stringio'
require 'erb'

module FlexView
  # View class which represents a full view which consists
  # of one root view file.
  class View
    @@initialized = false
    
    @@config =
    {
      :components =>
      {
        'fxv:out' =>
        {
          :namespace => 'http://www.windcoast.org/ruby/FlexView/namespaces/fxv',
          :class => 'FlexView::Components::Core::Out'
        },
        'fxv:if' =>
        {
          :namespace => 'http://www.windcoast.org/ruby/FlexView/namespaces/fxv',
          :class => 'FlexView::Components::Core::If'
        }
      }
    }
    
    @@logger = Logger.new(STDOUT)
    
    def self.logger
      @@logger
    end
    
    def self.config
      @@config
    end
    
    def self.register_component(prefix,namespace,class_name)
      
    end
    
    def self.configure
      yield @config
    end
    
    def initialize(filename)
      @compilation = nil

      # Read in root view file
      @viewFile = ViewFile.new(filename)

      # Check root node
      if @viewFile.rootNode.name != 'view'
        raise ParseException, "The initial element of each FlexView view file has to be <fxv:view>, element is [#{@viewFile.rootNode.name}]"
      end

      # Create component for root node
      @rootViewComponent = Components::Core::View.new(self, @viewFile.rootNode)
    end

    def compile
      @compilation = @rootViewComponent.compile
      FlexView.logger.info("View successfully compiled.")
      FlexView.logger.info @compilation
    end

    def render(local_assigns)
      # Compile if required to
      compile if !@compilation
      tmp_out = ERB.new(@compilation).result
      return tmp_out
    end
  end
end